package com.ak.server.platform.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ak.common.annotation.LogEndpoint;
import com.ak.common.controller.BaseController;
import com.ak.common.entity.AKResponse;
import com.ak.common.entity.router.VueRouter;
import com.ak.common.entity.system.Menu;
import com.ak.server.platform.service.IMenuService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;

/**
 * @author Vean
 */
@Api(tags = "菜单模块")
@Validated
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class MenuController extends BaseController {

    private final IMenuService menuService;

    @ApiOperation("获取用户菜单")
    @GetMapping("/{username}")
    public AKResponse getUserRouters(@NotBlank(message = "{required}") @PathVariable String username) {
        Map<String, Object> result = new HashMap<String, Object>(2);
        List<VueRouter<Menu>> userRouters = this.menuService.getUserRouters(username);
        String userPermissions = this.menuService.findUserPermissions(username);
        String[] permissionArray = new String[0];
        if (StringUtils.isNoneBlank(userPermissions)) {
            permissionArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(userPermissions, ",");
        }
        result.put("routes", userRouters);
        result.put("permissions", permissionArray);
        return new AKResponse().data(result);
    }

    @ApiOperation("获取可分配的菜单")
    @GetMapping
    public AKResponse menuList(Menu menu) {
    	List<Menu> menus = this.menuService.findMenuList(menu);
        return new AKResponse().data(menus);
    }

    @ApiOperation("新增菜单")
    @PostMapping
    @PreAuthorize("hasAuthority('menu:add')")
    @LogEndpoint(operation = "新增菜单/按钮", exceptionMessage = "新增菜单/按钮失败")
    public void addMenu(@Valid Menu menu) {
    	menu.setCreateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        this.menuService.createMenu(menu);
    }

    @ApiOperation("删除菜单")
    @DeleteMapping("/{menuIds}")
    @PreAuthorize("hasAuthority('menu:delete')")
    @LogEndpoint(operation = "删除菜单/按钮", exceptionMessage = "删除菜单/按钮失败")
    public void deleteMenus(@NotBlank(message = "{required}") @PathVariable String menuIds) {
    	Integer[] ids = Arrays.stream(Arrays.stream(menuIds.split(StringPool.COMMA)).mapToInt(Integer::parseInt).toArray()).boxed().toArray(Integer[]::new);
        this.menuService.deleteMeuns(ids);
    }

    @ApiOperation("修改菜单信息")
    @PutMapping
    @PreAuthorize("hasAuthority('menu:update')")
    @LogEndpoint(operation = "修改菜单/按钮", exceptionMessage = "修改菜单/按钮失败")
    public void updateMenu(@Valid Menu menu) {
    	menu.setUpdateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        this.menuService.updateMenu(menu);
    }

    @ApiOperation("导出全部菜单数据")
    @PostMapping("excel")
    @PreAuthorize("hasAuthority('menu:export')")
    @LogEndpoint(operation = "导出全部菜单数据", exceptionMessage = "菜单导出Excel失败")
    public void export(Menu menu, HttpServletResponse response) {
        List<Menu> menus = this.menuService.findMenuList(menu);
        ExcelKit.$Export(Menu.class, response).downXlsx(menus, false);
    }
}
